import Vue from 'vue'
import './assets/css/css.css'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'
import VueRouter from 'vue-router';
import echarts from 'echarts/lib/echarts';
import Axios from "axios";
import {
    BACKEND_ROOT
} from "~/Contants";
import '~/utils/LibFlexible';
import "~/interface/Cache";
import store from './vuex/store';
import jquery from 'jquery';
import routers from "~/router";
import {getPlatformCode} from "./interface/Common";
import {AuthConfig} from "./Contants";
import {INDEX, LOGIN} from "./router";
import AuthUtils from "./utils/AuthUtils";
import {NOT_FOUND} from "./router/FirstLevelRouter";
import {getCurrentUserInfo} from "~/interface/user";

Vue.prototype.$ = jquery
Vue.use(VueRouter);
Vue.use(ElementUI);
Vue.prototype.$echarts = echarts;
Vue.prototype.$http = Axios;

Axios.defaults.baseURL = BACKEND_ROOT;

// axios跨域携带Cookie
Axios.defaults.withCredentials = true;
// 路由配置
const RouterConfig = {
    mode: 'history',
    routes: routers,
}
const router = new VueRouter(RouterConfig)
const white = [LOGIN];
const loginWhite = [INDEX,NOT_FOUND];
router.beforeEach(async (to, from, next) => {
    // 自动尝试登陆
    const hasLogin = await AuthUtils.autoLogin();
    // 如果权限验证已关闭，直接允许访问
    if(!AuthConfig.authEnable) {
        console.log("已跳过权限验证，访问:",to)
        next();
        return;
    }
    // 如果目标在未登录白名单内，则可直接访问
    if(white.includes(to.name)){
        next();
        return;
    }
    if (hasLogin) {
        console.log(hasLogin);
        // 目标在已登录白名单或具备权限
        if(loginWhite.includes(to.name)||AuthUtils.hasAuth(to.name)){
            next()
        }else{
            console.warn("用户试图访问不具备权限的路由：",to);
            next({name:NOT_FOUND, query:{ to: to.fullPath }, params: to.params})
        }
    } else {
        // 未登录则重定向到登陆页面
        next({name: LOGIN, query:{ to: to.fullPath }, params: to.params})
    }
})


new Vue({
    el: '#app',
    router: router,
    store,
    render: h => h(App)
})
